package com.imooc.mail.service.impl;

import com.imooc.mail.dao.UserMapper;
import com.imooc.mail.enums.ResponseEnum;
import com.imooc.mail.pojo.User;
import com.imooc.mail.pojo.UserExample;
import com.imooc.mail.service.IUserService;
import com.imooc.mail.vo.ResponseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @Author wjc
 * Date on 2020/6/4 20:52
 */
@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;


    /**
     * 注册
     *
     * @param user
     * @return
     */
    @Override
    public ResponseVo<User> register(User user) {
        // 参数校验 校验邮箱，username是否重复
        UserExample userExample = new UserExample();
        userExample.createCriteria().andUsernameEqualTo(user.getUsername());
        long countByUserName = userMapper.countByExample(userExample);
        if (countByUserName > 0) {
            return ResponseVo.error(ResponseEnum.USERNAME_EXIST);
        }
        UserExample example = new UserExample();
        example.createCriteria().andEmailEqualTo(user.getEmail());
        long countByEmail = userMapper.countByExample(example);
        if (countByEmail > 0) {
            return ResponseVo.error(ResponseEnum.USEREMAIL_EXIST);
        }

        //md5摘要算法(Spring自带的)
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes(StandardCharsets.UTF_8)));

        // 将数据写入数据库
        int effect = userMapper.insertSelective(user);
        if (effect == 0) {
            return ResponseVo.error(ResponseEnum.ERROR);
        }
        return ResponseVo.success();
    }

    @Override
    public ResponseVo<User> login(User user) {
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes(StandardCharsets.UTF_8)));
        UserExample userExample = new UserExample();
        userExample.createCriteria()
                .andUsernameEqualTo(user.getUsername())
                .andPasswordEqualTo(user.getPassword());
        long count = userMapper.countByExample(userExample);
        if (count!=1){
            return ResponseVo.error(ResponseEnum.USER_ACCOUNT_OR_PWD_ERROR);
        }
        List<User> users = userMapper.selectByExample(userExample);
        users.get(0).setPassword("");
        return ResponseVo.success(users.get(0));
    }
}
